
import '../event/inventory_event.dart';
import '../event/read_block_event.dart';
import '../main.dart';
import 'send_helper.dart';


class InventoryManager{

  late InventoryManager manager;

  InventoryManager getManager(){
    return manager;
  }

  factory InventoryManager() => _singleton;

  static final InventoryManager _singleton = InventoryManager._internal();

  InventoryManager._internal();

  int count = 4;
  int time = 0;
  // Set<(String,String)> set = {};
  Set<String> set = {};

  var readBlockAnt = 1;
  List<String> rfidList = [];
  bool isReading = false;

  startInventory(int count){
    this.count = count;
    time = 0;
    set.clear();
    hfSerialPortHelper.sendData(inventory());
  }

  setInventoryResult(List<String> list){
    set.addAll(list);
    time++;
    if(time>=count){
      var data = set.toList();
      eventFactory.fire(InventoryEvent(data));
    }else{
      hfSerialPortHelper.sendData(inventory());
    }
  }


  addRfid(String rfid){
    rfidList.add(rfid);
    _readBlock();
  }

  addRfids(List<String> data){
    rfidList.addAll(data);
    _readBlock();
  }

  _readBlock(){
    if(isReading){
      return;
    }
    if(rfidList.isNotEmpty){
      readBlockAnt = 1;
      isReading = true;
      hfSerialPortHelper.sendData(readBlock(readBlockAnt,rfidList[0]));
    }else{
      eventFactory.fire(ReadBlockEvent((null,null)));
    }
  }

  _readNext(){
    rfidList.removeAt(0);
    _readBlock();
  }

  setReadBlockResult(String? block){
    isReading = false;
    if(rfidList.isNotEmpty){
      if(block != null){
        eventFactory.fire(ReadBlockEvent((rfidList[0],block)));
        _readNext();
      }else{
        if(readBlockAnt == 1){
          readBlockAnt = 2;
          isReading = true;
          hfSerialPortHelper.sendData(readBlock(readBlockAnt,rfidList[0]));
        }else{
          eventFactory.fire(ReadBlockEvent((rfidList[0],null)));
          _readNext();
        }
      }
    }
  }

}